/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function(mui, owner) {
	/*
	 * 判断是否支持沉浸式
	 */
	owner.isImmersed = function(){
		//判断是否支持沉浸式
		var isImmersedStatusbar = plus.navigator.isImmersedStatusbar();
		if(isImmersedStatusbar == true){
		 	//获取系统状态栏高度
			var statusbarHeight = plus.navigator.getStatusbarHeight();
			console.log(statusbarHeight);
//					var headerH = mui('.mui-bar-nav').height();
//					console.log(headerH);
//					mui('.mui-bar-nav').eq(0).css({height: (headerH + statusbarHeight)+'px', 'paddingTop':statusbarHeight+'px'}
//					 
			var nav = document.querySelector(".mui-bar-nav");
	        if(nav){
	            nav.style.cssText="height:67.5px; padding-top: "+statusbarHeight+"px;";
	        } else {
	            return;
	        }
		}
	}
	
	/**
	 * 获取应用本地配置
	 **/
	owner.setSetting = function(setting) {
		setting = setting || {};
		localStorage.setItem('shiquan_setting', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSetting = function() {
		var settingsText = localStorage.getItem('shiquan_setting') || "{}";
		var setting = JSON.parse(settingsText);
		if(setting.ServerUrl == undefined)
			setting.ServerUrl = "http://192.168.0.155:8090";
		return setting;
	}
	/**
	 * 获取用户阅读文档信息
	 **/
	owner.getDocuments = function() {
		var jsonString = localStorage.getItem('shiquan_documents') || "{}";
		return JSON.parse(jsonString);
	}
	/**
	 * 获取用户阅读文档信息
	 **/
	owner.getDocument = function(keyValue) {
		var docs = owner.getDocuments();
		console.log("getDocument="+JSON.stringify(docs));
		//return documents[keyValue];
		if(docs.ReadDocs == undefined)
			docs.ReadDocs = [];
		
		for(var index =0;index < docs.ReadDocs.length; index ++){
			var item = docs.ReadDocs[index];
			if(item.Id == keyValue){
				return item;
			}
		}
		return undefined;
	}
	/**
	 * 获取用户阅读文档信息
	 **/
	owner.addDocument = function(keyValue,doc) {	
		var docs = owner.getDocuments();
		//docs[keyValue] = doc;
		if(docs.ReadDocs == undefined)
			docs.ReadDocs = [];
		
		/*移除文件，让最新阅读的内容，放最前面。*/
		for(var index= docs.ReadDocs.length -1; index >= 0; index --){
			var item = docs.ReadDocs[index];
			if(item.Id == keyValue){
				docs.ReadDocs.splice(index,1);
			}
		}
		docs.ReadDocs.unshift(doc);/*头部添加*/
		
		var jsonString = JSON.stringify(docs);
		console.log("addDocument="+jsonString);
		localStorage.setItem('shiquan_documents', jsonString);
	}
	/**
	 * 保存用户阅读文档信息
	 **/
	owner.setDocuments = function(docs) {
		docs = docs || {};
		var jsonString = JSON.stringify(docs);
		console.log("setDocuments="+jsonString);
		localStorage.setItem('shiquan_documents', jsonString);
	}
	/**
	 * 删除用户阅读文档信息
	 **/
	owner.delDocument = function(keyValue) {
		var docs = owner.getDocuments();
		//docs[keyValue] = doc;
		if(docs.ReadDocs == undefined)
			docs.ReadDocs = [];
		
		/*移除文件，让最新阅读的内容，放最前面。*/
		for(var index= docs.ReadDocs.length -1; index >= 0; index --){
			var item = docs.ReadDocs[index];
			if(item.Id == keyValue){
				docs.ReadDocs.splice(index,1);
			}
		}
		var jsonString = JSON.stringify(docs);
		console.log("addDocument="+jsonString);
		localStorage.setItem('shiquan_documents', jsonString);
	}
	/**
	 * 清除用户阅读文档信息
	 **/
	owner.delDocuments = function() {
		var jsonString = JSON.stringify(docs);
		localStorage.setItem('shiquan_documents', jsonString);
	}
	/**
	 * 获取用户练习题目信息
	 **/
	owner.getPractices = function() {
		var jsonString = localStorage.getItem('shiquan_practices') || "{}";
		return JSON.parse(jsonString);
	}
	/**
	 * 获取用户练习题目信息
	 **/
	owner.getPractice = function(keyValue) {
		var objs = owner.getPractices();
		return objs[keyValue];
	}
	/**
	 * 增加用户练习题目信息
	 **/
	owner.addPractice = function(keyValue,practice) {	
		var objs = owner.getPractices();
		objs[keyValue] = practice;
		
		var jsonString = JSON.stringify(objs);
		console.log("addPractice="+jsonString);
		localStorage.setItem('shiquan_practices', jsonString);
	}
	/**
	 * 保存用户练习题目信息
	 **/
	owner.setPractices = function(practices) {
		practices = practices || {};
		localStorage.setItem('shiquan_practices', JSON.stringify(practices));
	}
	/**
	 * 初始用户考试及题目信息
	 **/
	owner.initSimulate = function(simulate) {
		simulate = simulate || {};
		localStorage.setItem('shiquan_simulates', JSON.stringify(simulate));
	}
	/**
	 * 获取用户考试及题目信息
	 **/
	owner.getSimulate = function() {
		var jsonString = localStorage.getItem('shiquan_simulates') || "{}";
		return JSON.parse(jsonString);
	}
	
	/**
	 * 获取用户考试题目信息
	 **/
	owner.getExamQuestion = function(keyValue) {
		var simulate = owner.getSimulate();
		//return objs[keyValue];
		if(simulate.ExamQuestions == undefined)
			simulate.ExamQuestions = [];
			
		for(var index =0;index < simulate.ExamQuestions.length; index ++){
			var item = simulate.ExamQuestions[index];
			if(item.Id == keyValue){
				return item;
			}
		}
		return undefined;
	}
	/**
	 * 增加用户考试题目信息
	 **/
	owner.saveExamQuestion = function(keyValue,examQuestion) {	
		var simulate = owner.getSimulate();
		//return objs[keyValue];
		if(simulate.ExamQuestions == undefined)
			simulate.ExamQuestions = [];
		
		/*移除文件，让最新阅读的内容，放最前面。*/
		for(var index= simulate.ExamQuestions.length -1; index >= 0; index --){
			var item = simulate.ExamQuestions[index];
			if(item.RefQuestionId == keyValue){
				simulate.ExamQuestions.splice(index,1);
			}
		}
		simulate.push(examQuestion);
		
		var jsonString = JSON.stringify(simulate);
		console.log("addSimulate="+jsonString);
		localStorage.setItem('shiquan_simulates', jsonString);
	}
	
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo,access_token, callback) {
		callback = callback || mui.noop;
// 		var users = JSON.parse(localStorage.getItem('$users') || '[]');
//		users.push(loginInfo);
		localStorage.setItem('$users', JSON.stringify(loginInfo[0])); 
		return owner.createState(loginInfo[0].userId,loginInfo[0].userName,access_token, callback);
		 
	};

	owner.createState = function(userId,userName,access_token, callback) {
		var state = owner.getState();
		state.account = userId;
		state.token = access_token;
		state.userName = userName;
		owner.setState(state);
		return callback();
	};
	
	owner.reflashUserInfo=function(userinfo)
	{
		localStorage.setItem('$users', JSON.stringify(userinfo));
		
		var state = owner.getState();
		state.account = userinfo.userId;
		state.userName = userinfo.userName;
		owner.setState(state);
	}

	/**
	 * 新用户注册
	 **/
	owner.register = function(registInfo, callback) {
		callback = callback || mui.noop;
		registInfo = registInfo || {};
//		regInfo.account = regInfo.account || '';
//		regInfo.password = regInfo.password || '';
//		if (regInfo.account.length < 5) {
//			return callback('用户名最短需要 5 个字符');
//		}
//		if (regInfo.password.length < 6) {
//			return callback('密码最短需要 6 个字符');
//		} 
//		var users = JSON.parse(localStorage.getItem('$users') || '[]');
//		users.push(regInfo);
		localStorage.setItem('$users', JSON.stringify(regInfo[0]));
		return callback();
	};
	
	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		//console.log(stateText);
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
	};

	owner.checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	owner.checkPhone = function(phone,callback) {
		phone = phone || '';
		var regx = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
		 if (!regx.test(phone)) {
            return callback('您输入的手机号有误。');
        };
        return callback('');
	};
	
	owner.isMobilePhone = function(phone) {
		phone = phone || '';
		var regx = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
		 if (!regx.test(phone)) {
            return false;
        };
        return true;
	};
	owner.isInt = function(val) {
		val = val || '';
		var regx = /^[0-9]*$/;
		 if (!regx.test(val)) {
            return false;
        };
        return true;
	};
	
	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || mui.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};
	
	owner.isIdCardNo= function(num) {
		    var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
		    var parityBit = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
		    var varArray = new Array();
		    var intValue;
		    var lngProduct = 0;
		    var intCheckDigit;
		    var intStrLen = num.length;
		    var idNumber = num;
		    // initialize
		    if ((intStrLen != 15) && (intStrLen != 18)) {
		        return false;
		    }
		    // check and set value
		    for (i = 0; i < intStrLen; i++) {
		        varArray[i] = idNumber.charAt(i);
		        if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
		            return false;
		        } else if (i < 17) {
		            varArray[i] = varArray[i] * factorArr[i];
		        }
		    }
		    if (intStrLen == 18) {
		        //check date
		        var date8 = idNumber.substring(6, 14);
		        if (isDate8(date8) == false) {
		            return false;
		        }
		        // calculate the sum of the products
		        for (i = 0; i < 17; i++) {
		            lngProduct = lngProduct + varArray[i];
		        }
		        // calculate the check digit
		        intCheckDigit = parityBit[lngProduct % 11];
		        // check last digit
		        if (varArray[17] != intCheckDigit) {
		            return false;
		        }
		    }
		    else {        //length is 15
		        //check date
		        var date6 = idNumber.substring(6, 12);
		        if (isDate6(date6) == false) {
		            return false;
		        }
		    }
		    return true;
		};

    function isDate8(sDate) {
	    if (!/^[0-9]{8}$/.test(sDate)) {
	        return false;
	    }
	    var year, month, day;
	    year = sDate.substring(0, 4);
	    month = sDate.substring(4, 6);
	    day = sDate.substring(6, 8);
	    var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
	    if (year < 1700 || year > 2500) return false
	    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1] = 29;
	    if (month < 1 || month > 12) return false
	    if (day < 1 || day > iaMonthDays[month - 1]) return false
	    return true
	}
	function isDate6(sDate) {
	    if (!/^[0-9]{6}$/.test(sDate)) {
	        return false;
	    }
	    var year, month, day;
	    year = 19+sDate.substring(0, 2);
	    month = sDate.substring(2, 4);
	    if (year < 1700 || year > 2500) return false
	    if (month < 1 || month > 12) return false
	    return true
	};
	
	
	owner.checklogin=function(){
		
		var state = owner.getState();
		if(owner.isnull(state.account)||owner.isnull(state.userName))
		{
			mui.openWindow({
				id: 'login',
				url: '/login.html',
				show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			});
		}
		else
		{
			return true;
		}
	}
	
	owner.loginstatus=function(){
		var state = owner.getState();
		if(owner.isnull(state.account)||owner.isnull(state.userName))
		{
			return false;
		}else
		{
			return true;
		}
	}
	owner.isnull =function(obj){
		if(obj==null||obj==undefined||obj=="{}"||obj=="")
		{
			return true;
		}
		else{
			return false;
		}
	}
	owner.setnullpic =function(obj,response){
		if (owner.isnull(response)|| owner.isnull(response.TABLE_NAME))
		{
			var nodata = obj.getElementsByClassName("div-not-data")[0];
		  
 	        if (nodata == undefined || nodata == null) {
	            var dv = document.createElement("div");
	            dv.setAttribute("id", "div-not-data");
	            dv.className= "div-not-data";
	            dv.setAttribute("align", "center");
	            dv.setAttribute("style", "display: block; position: absolute;top:50%;left:50%;margin-left: -10%;margin-top: -10%; text-align: center;vertical-align:middle; width: 20%;height: 20%;");
	            var img = "<img width='100%'  src='../images/nodata.png' />";
	            dv.innerHTML = img;
	            obj.appendChild(dv); 
	        }
		}
		else {
		    var nodata = obj.getElementsByClassName("div-not-data")[0];
		    if (nodata != undefined && nodata != null) nodata.parentNode.removeChild(nodata);
		} 
	}
	
	
	owner.lockOrientation=function(direction)
	{
		plus.screen.lockOrientation(direction);
		var version = parseFloat(mui.os.version);
		if (version < 4.0 || version >= 4.1) {
				plus.webview.currentWebview().setStyle({
				render: "always"
			});
		}
	}
	
}(mui, window.app = {}));